package com.pearadmin.pro.common.web.interceptor;

import cn.hutool.core.util.IdUtil;
import com.pearadmin.pro.common.constant.ConstantPool;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * Author: didiplus
 * Email: 972479352@qq.com
 * CreateTime: 2022/3/8
 * Desc:
 */
public class WebSocketInterceptor implements HandshakeInterceptor {

    /**
     * @Description: Handler处理前调用
     * @Param: [serverHttpRequest, serverHttpResponse, webSocketHandler, map]
     * @return: boolean
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
            //将uuid放到websocketsession中
            String uuid = IdUtil.simpleUUID();
            map.put(ConstantPool.USER_UUID_KEY,uuid);
            return  true;
        }else {
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }


}
